package com.blue.tooth.lock;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.blue.api.Common;
import com.blue.model.LogResp;
import com.blue.model.UploadResp;
import com.blue.tooth.lock.util.AppCache;
import com.blue.tooth.lock.util.BleSendDataUtil;
import com.blue.tooth.lock.util.DebugLogUtil;
import com.blue.tooth.lock.util.RetrofitUtil;
import com.blue.tooth.lock.util.SharePreferenceUtil;
import com.blue.tooth.lock.util.ToastUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.meihua.passivelock.BLEConnectCallback;
import com.meihua.passivelock.BLETools;
import com.meihua.passivelock.BleLockProCallback;
import com.meihua.passivelock.LogInfoVo;
import com.meihua.passivelock.fastble.BleManager;
import com.meihua.passivelock.fastble.data.BleDevice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * author: jiangliqiang
 * date:   2020/09/21
 * 连接钥匙
 * 1 需要实现BLEConnectCallback 蓝牙连接的回调接口
 * 2 需要实现BleLockProCallback 锁具通信的回调接口
 */
public class ConnectKeyAct extends Activity implements View.OnClickListener, BLEConnectCallback, BleLockProCallback, LifecycleOwner {
    private WebView mWebView;
    private TextView keyMac;
    private int limitPic;
    private ImageView iv;
    public static final int INPUT_FILE_REQUEST_CODE = 1;
    //    private ValueCallback<Uri> mUploadMessage;
//    private final static int FILECHOOSER_RESULTCODE = 2;
    private ValueCallback<Uri[]> mFilePathCallback;

    private String mCameraPhotoPath;
    private int CAMERA_REQUEST_CODE = 100;
    private int Disconnect_REQUEST_CODE = 200;
    private int Connect_REQUEST_CODE = 300;
    private boolean isConnected;
    private boolean isAutoConnect = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_lock_detail);
        isAutoConnect = getIntent().getBooleanExtra("isAutoConnect", true);
//        Beta.checkUpgrade();
        if (bluetoothAdapter == null) {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        XXPermissions.with(this).permission(Permission.Group.LOCATION).request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean all) {
                ConnectKeyAct.this.buildView();
                ConnectKeyAct.this.buildListener();
                initView();
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                finish();
            }
        });
//        initCheck();
    }

    /**
     * 每半秒 检查一次连接状态  2021年3月2日15:57:01
     */
    private CountDownTimer countDownTimer;
    private String testMac;

    private void initCheck() {

        if (countDownTimer == null) {
            // 倒计时
            // 总时间 24 * 60 * 60 * 1000，间隔 1000s 回调一次 onTick
            countDownTimer = new CountDownTimer(24 * 60 * 60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    testMac = new SharePreferenceUtil(getApplication()).getStrData("mac", "");
                    if (connectDevice != null) {
                        if (testMac.equals("")) {
                            testMac = connectDevice.getMac();
                            new SharePreferenceUtil(getApplication()).saveStrData("mac", testMac);
                        }
                        boolean test = BleManager.getInstance().isConnected(testMac);
//                        DebugLogUtil.getInstance().Debug(connectDevice.getName() + "---" + testMac + "," + test + StringUtil.stampToDate(System.currentTimeMillis() + ""));
                    } else {
//                        DebugLogUtil.getInstance().Debug("完犊子 断开啦" + testMac);
                    }
                }

                @Override
                public void onFinish() {
                    // 倒计时结束时的回调
                }
            };
            countDownTimer.cancel();
            countDownTimer.start();
        }

    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initView() {
        iv = findViewById(R.id.iv);
        iv.setOnClickListener(this);
        //加载网页链接
        String url = RetrofitUtil.Host + "/index/people/index";
//        String url = "http://srg.quanjing-vr.com/index.php?s=/wap/index/index2";
        WebSettings webSettings = mWebView.getSettings();
//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        } else {
            try {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
// 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);// 支持 localstorage
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAppCacheEnabled(true);

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setAllowContentAccess(true);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDatabaseEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                Log.d(DebugLogUtil.getInstance().getFilter(), "开始加载");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                Log.d(DebugLogUtil.getInstance().getFilter(), "加载结束");
            }

            // 链接跳转都会走这个方法
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(DebugLogUtil.getInstance().getFilter(), "Url：" + url);
                if (url.contains("http")) {
                    view.loadUrl(url);// 强制在当前 WebView 中加载 url
                    return true;
                } else {
//                    if (!AppCache.isInstallApp(getApplication(), url)) {
                    if (!AppCache.isInstallApp("com.autonavi.minimap", getApplication())) {
                        ToastUtils.show(getApplication(), "高德地图未安装");
                        mWebView.goBack();
                        return false;
                    }
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

            }


        });
        mWebView.clearCache(true);
        mWebView.clearHistory();
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
//                Log.d(DebugLogUtil.getInstance().getFilter(), "newProgress：" + newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                Log.d(DebugLogUtil.getInstance().getFilter(), "标题：" + title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//                ToastUtils.show(getApplicationContext(), "onJsAlert");
                DebugLogUtil.getInstance().Debug(message);
                connect();
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                String msg = consoleMessage.message();
//                ToastUtils.show(getApplicationContext(), msg);
                DebugLogUtil.getInstance().Debug(msg);
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;

                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    // Create the File where the photo should go
                    File photoFile = null;
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(photoFile));
                    } else {
                        takePictureIntent = null;
                    }
                }

                Intent contentSelectionIntent = new Intent(Intent.ACTION_CAMERA_BUTTON);//Intent.ACTION_GET_CONTENT
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");

                Intent[] intentArray;
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

                startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

                return true;
            }


        });
        initJsApi();
        mWebView.loadUrl(url);
    }

    @Override
    public void onBackPressed() {
        disconnectAll();
        DebugLogUtil.getInstance().Debug(mWebView.canGoBack() + "onBackPressed");
        super.onBackPressed();
    }

    //在sdcard卡创建缩略图
    //createImageFileInSdcard
    @SuppressLint("SdCardPath")
    private File createImageFile() {
        //mCameraPhotoPath="/mnt/sdcard/tmp.png";
        File file = new File(Environment.getExternalStorageDirectory() + "/", "tmp.png");
        mCameraPhotoPath = file.getAbsolutePath();
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    private void initJsApi() {
        //核心方法, 用于处理JavaScript被执行后的回调
//        mWebView.addJavascriptInterface(new AndroidtoJs(this), "zhuochuang");
        mWebView.addJavascriptInterface(new AndroidApi(), "zhuochuang");

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == Disconnect_REQUEST_CODE) {// 接收mainactivity的旨意   断开连接
                if (data != null) {
                    boolean isConnect = data.getBooleanExtra("opt", true);
                    if (isConnect == false) {
                        disconnectAll();
                    } else {
                        ConnectKeyAct.this.connect();
                    }
                }
            } else if (requestCode == CAMERA_REQUEST_CODE) {
                String s = "";
                File f = null;
                if (isAndroidQ) {
                    // Android 10 使用图片uri加载
                    iv.setImageURI(mCameraUri);
                    f = uriToFileApiQ(mCameraUri);
                    if (f == null) {
                        ToastUtils.show(getApplication(), "未获取到图片");
                        return;
                    }
                    s = f.getAbsolutePath();
                } else {
                    // 使用图片路径加载
                    s = mCameraImagePath;
                    Bitmap bit = BitmapFactory.decodeFile(mCameraImagePath);
                    iv.setImageBitmap(bit);
                }
                DebugLogUtil.getInstance().Debug(s);
//                mWebView.evaluateJavascript("javascript:cameraCallBack(" + s + ")", null);
                reqUpload1(s);
            }
        }
    }

    /**
     * 上传图片
     *
     * @param s
     */
    private void reqUpload1(String s) {


        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), new File(s));
        RetrofitUtil.addUrlApi(getApplication(), Common.class).uploadImage(requestFile).enqueue(new Callback<UploadResp>() {
            @Override
            public void onResponse(Call<UploadResp> call, Response<UploadResp> response) {
                UploadResp bean = response.body();
                if (bean == null) {
                    return;
                }
                String url = bean.getUrl();
                if (url == null) {
                    ToastUtils.show(getApplication(), "上传成功，解析失败");
                    return;
                }
                mWebView.evaluateJavascript("javascript:if(window.cameraCallBack){window.cameraCallBack('" + url + "')}", null);

                DebugLogUtil.getInstance().Debug(response.message());
            }

            @Override
            public void onFailure(Call<UploadResp> call, Throwable t) {
                DebugLogUtil.getInstance().Error(getApplication(), t.getMessage());
            }
        });


    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return new Lifecycle() {
            @Override
            public void addObserver(@NonNull LifecycleObserver observer) {

            }

            @Override
            public void removeObserver(@NonNull LifecycleObserver observer) {

            }

            @NonNull
            @Override
            public State getCurrentState() {
                return null;
            }
        };
    }


    class AndroidApi {
        @JavascriptInterface
        public void camera111() {
            XXPermissions.with(ConnectKeyAct.this).permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean all) {
                    takeCamera();
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {

                }
            });
        }

        @JavascriptInterface
        public void chooseImage(int divId, int limit) {
//            limitPic = new Integer(limit);
            limitPic = limit;
        }


        @JavascriptInterface
        public void conncetBle(String userid) {
//            ToastUtils.show(ConnectKeyAct.this, "使用者：" + USERID);
//            connect(); //连接操作，用不到了 2020年9月27日10:39:19
        }

        @JavascriptInterface
        public void initLock(String mLockCode) {
            LOCK_CODE = mLockCode;
            initKey(mLockCode);// 初始化锁
        }

        //  开锁任务授权
        @JavascriptInterface
        public void authLock(String userId, String start, String end, String code) {
            ToastUtils.show(getApplicationContext(), "authLock");
//            authAction("9999", start, end, code);// 授权
            USERID = userId;
            new SharePreferenceUtil(getApplication()).saveStrData("uid", userId);
            LOCK_CODE = code;
            authAction(userId, start, end, LOCK_CODE);// 授权
        }

        /**
         * 清除授权
         */
        @JavascriptInterface
        public void clearAuthApi() {
            clearAuth(); // 清除授权
        }

        @JavascriptInterface
        public void clearLock(String lockCode) {
            lockCode = LOCK_CODE;
            clearLockApi(lockCode); // 清空锁芯
        }

        @JavascriptInterface
        public void getLockInfo() {
            getLockInfoApi(); // 清除授权
        }

        @JavascriptInterface
        public void disConnect123() {
            bleTools.disConnect(); //
        }

        @JavascriptInterface
        public void toBleList(String userId) {
//   判断当前连接状态
            new SharePreferenceUtil(getApplication()).saveStrData("uid", userId);
            startActivityForResult(new Intent(getApplicationContext(), MainActivity.class), Disconnect_REQUEST_CODE);
        }


    }

    //用于保存拍照图片的uri
    private Uri mCameraUri;

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;

    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
    // 申请相机权限的requestCode
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;


    /**
     * 调起相机拍照
     */
    private void takeCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                photoFile = createImageFile();

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                    } else {
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }

            mCameraUri = photoUri;
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

    //content://media/external/images/media/13239    content://media/external/images/media/13240
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public File uriToFileApiQ(Uri uri) {
        File file = null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    InputStream is = contentResolver.openInputStream(uri);
                    File cache = new File(getExternalCacheDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                    FileOutputStream fos = new FileOutputStream(cache);
                    FileUtils.copy(is, fos);
                    file = cache;
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }


    private void clearLockApi(final String lockCode) {
        if (mac == null || lockCode == null) {
            ToastUtils.show(ConnectKeyAct.this, "请重新连接设备");
            return;
        }
        type = 3;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BleSendDataUtil.resetLock(bleTools, lockCode, mac, USERID);
            }
        });
    }

    private void clearAuth() {
        log.setText("准备清空授权");
        type = 2;
        Log.i(TAG, "cancelAuth");

        BleSendDataUtil.cleanAuth(bleTools);
    }

    private void getLockInfoApi() {

        bleTools.setLockRespCallBack(new BleLockProCallback() {
            @Override
            public void bindKeyCallback(boolean b) {

            }

            @Override
            public void verificationTimeCallback(boolean b, boolean b1) {

            }

            @Override
            public void dumpEnergyCallBack(int i) {

            }

            @Override
            public void authKeyCallBack(boolean b) {
                DebugLogUtil.getInstance().Debug("authKeyCallBack" + b);
            }

            @Override
            public void initLockCallBack(boolean b) {

            }

            @Override
            public void getKeyLogCallBack(LogInfoVo logInfoVo) {
                if (logInfoVo != null) {
//                    Log.d(DebugLogUtil.getInstance().getFilter(), logInfoVo.lockCode);
//                    Log.d(DebugLogUtil.getInstance().getFilter(), logInfoVo.lockMac);
//                    Log.d(DebugLogUtil.getInstance().getFilter(), logInfoVo.logNub);
//                    Log.d(DebugLogUtil.getInstance().getFilter(), logInfoVo.toString());
                }

            }

            @Override
            public void lockInfoCallBack(String s) {
                ToastUtils.show(ConnectKeyAct.this, s, Toast.LENGTH_LONG);
            }

            @Override
            public void setWorkModeCallBack(int i, int i1) {

            }
        });

        bleTools.getLockInfo();
        bleTools.getLockLog();
    }

    private void buildView() {
        mWebView = findViewById(R.id.web);
        lockName = findViewById(R.id.lockName);
//        lockMac = findViewById(R.id.lockMac);
        electricNum = findViewById(R.id.electricNum);
        connectStatus = findViewById(R.id.connectStatus);
        initLock = findViewById(R.id.initLock);
        auth = findViewById(R.id.auth);
        cancelAuth = findViewById(R.id.cancelAuth);
        loadText = findViewById(R.id.loadText);
        iv_running = findViewById(R.id.iv_running);
        loadingBox = findViewById(R.id.loadingBox);
//        lockCodeEt = findViewById(R.id.lockCodeEt);
        clearLock = findViewById(R.id.clearLock);
        back = findViewById(R.id.back);
        log = findViewById(R.id.log);
        lockCode = findViewById(R.id.lockCode);
        getLockInfo = findViewById(R.id.getLockInfo);
        getOpenLockInfo = findViewById(R.id.getOpenLockInfo);
        lockName = findViewById(R.id.lockName);
        keyMac = findViewById(R.id.keyMac);
        electricNum = findViewById(R.id.electricNum);
        connectStatus = findViewById(R.id.connectStatus);
        initLock = findViewById(R.id.initLock);
        auth = findViewById(R.id.auth);
        cancelAuth = findViewById(R.id.cancelAuth);
        loadText = findViewById(R.id.loadText);
        iv_running = findViewById(R.id.iv_running);
        loadingBox = findViewById(R.id.loadingBox);
//        lockCodeEt = findViewById(R.id.lockCodeEt);
        clearLock = findViewById(R.id.clearLock);
        log = findViewById(R.id.log);
        lockCode = findViewById(R.id.lockCode);
        getLockInfo = findViewById(R.id.getLockInfo);
        getOpenLockInfo = findViewById(R.id.getOpenLockInfo);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String name = bundle.getString("name");
            mac = bundle.getString("mac");
// 不再从上一界面获取             USERID = bundle.getString("userId");
            lockName.setText("钥匙名称:" + name);
        }

        keyMac.setText("钥匙mac:" + mac);
        lockMode = findViewById(R.id.lockMode);
        switchLockMode = findViewById(R.id.switchLockMode);
    }

    private TextView lockMode;
    private Button switchLockMode;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void buildListener() {
        initLock.setOnClickListener(this);
        auth.setOnClickListener(this);
        cancelAuth.setOnClickListener(this);
        back.setOnClickListener(this);
        getOpenLockInfo.setOnClickListener(this);
        getLockInfo.setOnClickListener(this);
        clearLock.setOnClickListener(this);
        switchLockMode.setOnClickListener(this);
    }

    private void connect() {
        loadText.setText("正在连接蓝牙");
        loadingBox.setVisibility(View.VISIBLE);
        this.startScanAnim();
        if (bleTools == null) {
            bleTools = new BLETools();
            bleTools.setConnectCallBack(this);
            bleTools.setLockRespCallBack(this);
        }
        bleTools.connect(AppCache.getBleDevice());
    }

    private void startScanAnim() {
        iv_running.setVisibility(View.VISIBLE);
        anim = (AnimationDrawable) iv_running.getDrawable();
        iv_running.post(new Runnable() {
            @Override
            public void run() {
                anim.start();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DebugLogUtil.getInstance().Debug("onDestroy");
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        DebugLogUtil.getInstance().Debug("onStop");
    }

    private BluetoothAdapter bluetoothAdapter;

    private void disconnectAll() {
        ToastUtils.show(this, "正在断开");
        if (connectDevice != null) {
            BleManager.getInstance().disconnect(connectDevice);
        }
        if (bleTools != null) {
            bleTools.disConnect();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv:
                disconnectAll();
                break;
            case R.id.switchLockMode:
                toswitchLockMode();
                break;
            case R.id.initLock:
                initKey("");
                break;
            case R.id.auth:
                authAction("99999", "", "", LOCK_CODE);
                break;
            case R.id.cancelAuth:
                clearAuth();
                break;
            case R.id.getOpenLockInfo:
                log.setText("准备获取日志");
                getLog();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.getLockInfo:
                bleTools.getLockInfo();
                break;
            case R.id.clearLock:
                clearLockApi(LOCK_CODE);
                break;
            default:
                break;
        }
    }

    private void getLog() {
        logSb.setLength(0);
        BleSendDataUtil.getKeyLogCallBack(bleTools);
    }

    private void toswitchLockMode() {
        bleTools.setWorkMode(0);
        bleTools.getLockInfo();
    }

    private void initKey(String mLockCode) {
        log.setText("准备向锁授权");
        if (mLockCode.equals("")) {
        }
//        mLockCode = LOCK_CODE;
        LOCK_CODE = mLockCode;

        Log.i(TAG, "mLockCode:" + mLockCode);
        BleSendDataUtil.initLock(bleTools, mLockCode);
    }

    /**
     * @param userId 999
     * @param start  20200922120000
     * @param end    20201222120000
     */
    private void authAction(String userId, String start, String end, String code) {
        type = 1;
        String lockCode = code;
        lockCode = lockCode.replaceAll(":", "");
        BleSendDataUtil.authAction(bleTools, userId, lockCode, mac, start, end);
    }

    //蓝牙连接成功
    @Override
    public void connectSuccess(BleDevice bleDevice) {
        anim.stop();
        String macS = bleDevice.getMac();
        mac = macS;
        if (!isConnected) {
            loadingBox.setVisibility(View.GONE);
            this.connectDevice = bleDevice;
            connectStatus.setText("连接成功");
            ToastUtils.show(this, "连接状态:连接成功" + USERID);
            USERID = new SharePreferenceUtil(getApplication()).getStrData("uid", "");
            if (USERID.equals("")) {
                ToastUtils.show(this, "无用户ID");
                return;
            }
            bleTools.getLockInfo();

            BleSendDataUtil.bindKey(bleTools, USERID);
            mWebView.evaluateJavascript("javascript:if(window.macCallBack123){window.macCallBack123('" + macS + "')}", null);
            isConnected = true;
        } else {
            DebugLogUtil.getInstance().Debug("重复进入成功回调....");
        }
        getLog();
        DebugLogUtil.getInstance().Debug(macS);

//        通知webview
    }

    /**
     * 连接成功 -- 获取电量成功  --绑定成功 --- 上传日志
     */

    private void enabledButton() {
        initLock.setEnabled(true);
        switchLockMode.setEnabled(true);
        initLock.setBackgroundResource(R.drawable.login_btn_selector);
        switchLockMode.setBackgroundResource(R.drawable.login_btn_selector);
        auth.setEnabled(true);
        auth.setBackgroundResource(R.drawable.login_btn_selector);
        cancelAuth.setEnabled(true);
        cancelAuth.setBackgroundResource(R.drawable.login_btn_selector);
        getOpenLockInfo.setEnabled(true);
        getOpenLockInfo.setBackgroundResource(R.drawable.login_btn_selector);
        getLockInfo.setEnabled(true);
        getLockInfo.setBackgroundResource(R.drawable.login_btn_selector);
        clearLock.setEnabled(true);
        clearLock.setBackgroundResource(R.drawable.login_btn_selector);
    }

    //蓝牙连接失败
    @Override
    public void connectFailed() {
        anim.stop();
        loadingBox.setVisibility(View.GONE);
        connectDevice = null;
        connectStatus.setText("连接状态:连接失败");
    }

    //蓝牙断开连接
    @Override
    public void onDisConnected(BleDevice bleDevice) {
        loadingBox.setVisibility(View.GONE);
        ToastUtils.show(this, "设备已断开~");
        connectDevice = null;
//        isConnected = false;
        connectStatus.setText("连接状态:断开");
    }

    //用户id与钥匙绑定回调
    @Override
    public void bindKeyCallback(boolean isBindSuccess) {
        if (isBindSuccess) {
            log.setText("钥匙绑定成功");
            ToastUtils.show(this, "绑定成功");
            BleSendDataUtil.setKeyTime(bleTools);
        } else {
            log.setText("钥匙绑定失败");
        }
    }

    //校时回调
    @Override
    public void verificationTimeCallback(boolean isVerificationTimeSuccess, boolean isOnline) {
        if (isVerificationTimeSuccess) {
            log.setText("时间校验成功");
        } else {
            log.setText("时间校验失败");
        }
        BleSendDataUtil.getElectricity(bleTools);
    }

    //电量回调
    @Override
    public void dumpEnergyCallBack(int dumpEnergy) {
        if (dumpEnergy > 100) {
            dumpEnergy = 100;
        }
        electricNum.setText("锁具电量:" + dumpEnergy + "%");

        enabledButton();
        ToastUtils.show(this, "获取电量成功");
        mWebView.evaluateJavascript("javascript:if(window.electricity){window.electricity('" + dumpEnergy + "')}", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
//                                    ToastUtils.show("onReceiveValue:" + value);
            }
        });
    }

    //授权回调
    @Override
    public void authKeyCallBack(boolean isAuthSuccess) {
        Log.i(TAG, "isAuthSuccess:" + isAuthSuccess);
        String msg = "";
        if (isAuthSuccess) {
            if (type == 3) {
                Toast.makeText(this, "将钥匙插入锁芯,听到 滴滴 两声代表清除成功", Toast.LENGTH_LONG);
                return;
            }
            if (type == 1) {
                msg = "授权成功";
                log.setText(msg);
            } else if (type == 2) {
                msg = "清除授权成功";
                log.setText(msg);
            }
        } else {
            if (type == 1) {
                msg = "授权失败";
            } else if (type == 2) {
                msg = "清除授权失败";
            } else if (type == 3) {
                msg = "清除锁芯失败";
            }
            log.setText(msg);
        }
        ToastUtils.show(this, msg);
    }

    //初始化锁具回调
    @Override
    public void initLockCallBack(boolean isSuccess) {
        if (isSuccess) {
            ToastUtils.show(this, "初始化锁具成功");
            log.setText("初始化锁具成功");
        } else {
            ToastUtils.show(this, "初始化锁具失败");
//            log.setText("初始化锁具失败");
        }
    }

    @Override
    public void getKeyLogCallBack(LogInfoVo logInfoVo) {
        if (logInfoVo == null) {
            if (logSb.length() == 0) {
                log.setText("没有日志");
            }
            return;
        }
        LOCK_CODE = logInfoVo.lockCode.replace("-", ":").toUpperCase();
        int openType = new Integer(logInfoVo.openType);
        uploadLog(openType);
        logSb.append("用户:").append(logInfoVo.logNub).append(",");//ee99:5066:4526:b4a9:ae4a:711e:ef09:c75c
        logSb.append(logInfoVo.openTime);
        if (logInfoVo.openType.equals("00")) {
            if (logInfoVo.result.equals("01")) {
                logSb.append("  关锁成功");
            } else {
                logSb.append(" 关锁失败");
            }
        } else if (logInfoVo.openType.equals("01")) {
            if (logInfoVo.result.equals("01")) {
                logSb.append("  开锁成功");
            } else {
                logSb.append(" 开锁失败");
            }
        } else if (logInfoVo.openType.equals("01")) {
            logSb.append("  清除锁识别号");
        } else {
            logSb.append("  执行:").append(logInfoVo.openType);
        }
        logSb.append("\r\n");
        log.setText(logSb.toString());
        RetrofitUtil.addUrlApi(getApplication(), Common.class).upload_log(logInfoVo.logNub, logInfoVo.lockMac, logInfoVo.lockCode, logInfoVo.openType).enqueue(new Callback<LogResp>() {
            @Override
            public void onResponse(Call<LogResp> call, Response<LogResp> response) {
                LogResp bean = response.body();
                if (bean != null) {
//                    ToastUtils.show(ConnectKeyAct.this, bean.get_$0() + "");
                    DebugLogUtil.getInstance().Debug(response.message());
                } else {
//                    ToastUtils.show(getApplicationContext(), "返回数据有误");
                    DebugLogUtil.getInstance().Error(getApplicationContext(), "返回数据有误");
                }

            }

            @Override
            public void onFailure(Call<LogResp> call, Throwable t) {
                DebugLogUtil.getInstance().Error(getApplication(), t.getMessage());
            }
        });
        BleSendDataUtil.getKeyLogCallBack(bleTools);//重复读取日志，直到logInfoVo为空
    }

    @Override
    public void lockInfoCallBack(String lockMac) {
        lockCode.setText("锁具信息:" + lockMac);
//        log.setText("锁具mac-16进制:" + lockMac);
    }

    @Override
    public void setWorkModeCallBack(int i, int i1) {
        DebugLogUtil.getInstance().Debug(i + "," + i1);
    }


    private void uploadLog(int type) {
        if (LOCK_CODE.equals("")) {
//         9   SharedPreferences sp = getSharedPreferences(SHARED_KEY, Context.MODE_PRIVATE);
//            LOCK_CODE = sp.getString("lockCode", "-");
        }
//        LOCK_CODE = "0021:0002:0004:0000:C718:0000:0000:0000";
        LOCK_CODE = LOCK_CODE.toUpperCase();
        USERID = new SharePreferenceUtil(getApplication()).getStrData("uid", "");
        if (USERID.equals("")) {
            ToastUtils.show(this, "无用户ID");
            return;
        }
        DebugLogUtil.getInstance().Debug("提交日志" + LOCK_CODE);
        RetrofitUtil.addUrlApi(getApplication(), Common.class).upload_log(USERID, mac, LOCK_CODE + "", type + "").enqueue(new Callback<LogResp>() {
            @Override
            public void onResponse(Call<LogResp> call, Response<LogResp> response) {
                LogResp bean = response.body();
                if (bean != null) {
                    ToastUtils.show(ConnectKeyAct.this, bean.get_$0() + "");
                    DebugLogUtil.getInstance().Debug(response.message());
                } else {
                    ToastUtils.show(getApplicationContext(), "返回数据有误");
                }

            }

            @Override
            public void onFailure(Call<LogResp> call, Throwable t) {
                DebugLogUtil.getInstance().Error(getApplication(), t.getMessage());
            }
        });
    }

    /**
     * 0050:0001:0010:0000:1a2b:0000:0000:0000"  、 9999  可开锁。
     */
    //蓝牙相关
    private BLETools bleTools;
    private BleDevice connectDevice;//连接成功的蓝牙

    private AnimationDrawable anim;
    private final String TAG = DebugLogUtil.getInstance().getFilter();
    private String USERID = "";//99999999 9999
    private String LOCK_CODE = "0050:0001:0010:0000:1a2b:0000:0000:0005";//0050:0001:0010:0000:1a2b:0000:0000:0005 0021:0002:0004:0000:C718:0000:0000:0000   0033:0001:0008:0000:1d25:0000:0000:0000   0050:0001:0010:0000:1a2b:0000:0000:0000
    private String mac;
    private int type = 0;
    private StringBuffer logSb = new StringBuffer();

    private TextView loadText;
    private ImageView iv_running;
    private TextView log;
    private TextView lockName;
    private TextView lockMac;
    private TextView electricNum;
    private TextView connectStatus;
    private Button initLock;
    private Button auth;
    private Button cancelAuth;
    private Button getOpenLockInfo;
    private LinearLayout loadingBox;
    private Button getLockInfo;
    private Button clearLock;
    private TextView back;
    //    private EditText lockCodeEt;
    private TextView lockCode;
    private final String SHARED_KEY = "demoBluetooth";
}
